package cat.music.ut.viewmodel

import androidx.lifecycle.MutableLiveData
import cat.music.ut.bean.SearchResult
import cat.music.ut.bean.parseAudioInfo
import cat.music.ut.comm.http.OkHttpUtil
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject

class SearchViewModel : BaseViewModel() {
    val mldSearchResult = MutableLiveData<MutableList<SearchResult>>()
    fun search(key: String, page: Int = 0) {
        coroutinesHttp {
            val string =
                OkHttpUtil.get("https://www.kuwo.cn/search/searchMusicBykeyWord?vipver=1&client=kt&ft=music&cluster=0&strategy=2012&encoding=utf8&rformat=json&mobi=1&issubtitle=0&show_copyright_off=1&pn=${page}&rn=20&all=${key}")
            val jsonArray = JSON.parseObject(string).getJSONArray("abslist")
            val searchList = mutableListOf<SearchResult>()
            jsonArray.forEach {
                it as JSONObject
                val songName: String = it.getString("SONGNAME")
                val pic: String = "https://img2.kuwo.cn/star/albumcover/"+it.getString("web_albumpic_short")
                val audioInfos = parseAudioInfo(it.getString("N_MINFO"))
                val artist: String = it.getString("ARTIST")
                val musicID: String = it.getString("MUSICRID")
                val album: String = it.getString("ALBUM")
                val element =
                    SearchResult(songName, pic, audioInfos.toMutableList(), artist, musicID, album)
                searchList.add(element)
            }
            mldSearchResult.postValue(searchList)
        }
    }
}